import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author：ricardo
 * @Version：1.0
 * @Date：2021/11/5-16:06
 * @Since:jdk1.8
 * @Description:
 */
public class HttpClientDemo {
    public static void main(String[] args) {
//        get();
//        post();
//        delete();
//        postForJson();
        restTemplate();
    }

    /**
     * get请求
     */
    public static void get() {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        HttpEntity entity = null;
        //1.创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder();
        //2.设置uri路径
        uriBuilder.setPath("http://api.tianapi.com/aqi/index");
        //3.设置编码格式
        uriBuilder.setCharset(Charset.forName("utf-8"));
        HashMap<String, String> map = new HashMap<>();

        map.put("key", "63cea1835584c41fbeef939bfde87296");
        map.put("area", "上海");

        Set<Map.Entry<String, String>> entries = map.entrySet();
        entries.forEach(entry -> {
            String key = entry.getKey();
            String value = entry.getValue();
            //4.设置请求参数
            uriBuilder.addParameter(key, value);
        });
        //5.创建uri
        try {
            URI uri = uriBuilder.build();
            //6.设置请求方式
            httpGet = new HttpGet(uri);
            //6.1.设置请求头:当客户端关闭时,通知服务器断开连接
            httpGet.setHeader(HttpHeaders.CONNECTION, "close");
            //7.创建httpClient客户端
            httpClient = HttpClients.createDefault();
            //8.发送请求
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            //9.根据httpResponse获取响应状态码
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            //10.如果状态码是200,获取响应体
            if (statusCode == HttpStatus.SC_OK) {
                entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity, "utf-8");
                System.out.println(result);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            release(httpClient, httpGet, null,entity);
        }
    }

    /**
     * post请求
     */
    public static void post() {
        CloseableHttpClient httpClient=null;
        HttpPost httpPost=null;
        HttpEntity responseEntity=null;
        String path = "http://api.tianapi.com/aqi/index";
        String charset = "utf-8";
        //1.创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder();
        try {
            //2.设置url路径
            uriBuilder.setPath(path);
            //3.设置编码格式
            uriBuilder.setCharset(Charset.forName(charset));
            HashMap<String, String> map = new HashMap<>();
            map.put("key", "63cea1835584c41fbeef939bfde87296");
            map.put("area", "广州");
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            entrySet.forEach(entry -> {
                String value = entry.getValue();
                String key = entry.getKey();
                //4.拼接请求参数
                uriBuilder.addParameter(key,value);
            });
            //5.创建uri
            URI uri = uriBuilder.build();
            //6.设置请求方式为post
            httpPost= new HttpPost(uri);
            httpPost.setHeader(HttpHeaders.CONNECTION,"close");
            //设置请求头:提交的表单格式
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE,"application/x-www-form-urlencoded");
            //7.创建httpClient客户端
            httpClient = HttpClients.createDefault();
            //8.发送请求
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            //9.获取响应状态码
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode==HttpStatus.SC_OK){
                responseEntity= httpResponse.getEntity();
                String result = EntityUtils.toString(responseEntity);
                System.out.println(result);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            release(httpClient,null,httpPost,responseEntity);
        }
    }

    /**
     * delete请求
     */
    public static void delete(){
        HttpDelete httpDelete=null;
        CloseableHttpClient httpClient=null;
        HttpEntity responseEntity=null;
        String path="http://localhost:8080/findAll";
        String charset="utf-8";
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setPath(path);
        uriBuilder.setCharset(Charset.forName(charset));
        uriBuilder.addParameter("id","1001");
        try {
            URI uri = uriBuilder.build();
            httpDelete = new HttpDelete(uri);
            httpDelete.setHeader(HttpHeaders.CONNECTION,"close");
            httpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = httpClient.execute(httpDelete);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode==HttpStatus.SC_OK){
                //获取响应体
                responseEntity = httpResponse.getEntity();
                String result = EntityUtils.toString(responseEntity, charset);
                System.out.println(result);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            release(httpClient,null,null,responseEntity);
        }
    }

    /**
     * postForJson
     */
    public static void postForJson(){
        HttpPost httpPost=null;
        CloseableHttpClient httpClient=null;
        HttpEntity responseEntity=null;
        String path= "http://localhost:8080/findAll";
        String charset="utf-8";
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setCharset(Charset.forName(charset));
        uriBuilder.setPath(path);
        try {
            URI uri = uriBuilder.build();
            httpPost= new HttpPost(uri);
            httpPost.setHeader(HttpHeaders.CONNECTION,"close");
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE,"application/json");
            Admin admin= new Admin();
            admin.setUsername("张三");
            admin.setPassword("123321");
            String reqJsonStr = JSON.toJSONString(admin);
            StringEntity stringEntity = new StringEntity(reqJsonStr, charset);
            httpPost.setEntity(stringEntity);
            httpClient= HttpClients.createDefault();
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode==HttpStatus.SC_OK){
                responseEntity= httpResponse.getEntity();
                String result = EntityUtils.toString(responseEntity, charset);
                System.out.println(result);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            release(httpClient,null,httpPost,responseEntity);
        }
    }

    /**
     *RestTemplate
     */
    public static void restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        String path="http://api.tianapi.com/aqi/index?key=63cea1835584c41fbeef939bfde87296&area=上海";
        String forObject = restTemplate.getForObject(path, String.class);
        System.out.println(forObject);
    }
    /**
     * 释放资源
     *
     * @param httpClient
     * @param httpGet
     * @param entity
     */
    public static void release(CloseableHttpClient httpClient, HttpGet httpGet,HttpPost httpPost, HttpEntity entity) {
        try {
            if (entity != null) {
                EntityUtils.consume(entity);
            }
            if (httpGet != null) {
                httpGet.abort();
            }
            if (httpPost!=null) {
                httpPost.abort();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
